import { Component, OnInit, OnChanges, SimpleChanges, Input } from '@angular/core';

declare var AMap: any;

@Component({
  selector: 'app-b-map',
  templateUrl: './b-map.component.html',
  styleUrls: ['./b-map.component.scss']
})
export class BMapComponent implements OnChanges {
  public map: any;
  public overlayGroup: any;
  public cluster: any;
  @Input() points: Array<any>;

  constructor() {}

  initMap() {
    this.map = new AMap.Map('aMap', {
      resizeEnable: true, // 是否监控地图容器尺寸变化
      zoom: 11, // 初始化地图层级
      center: [108.948063, 34.259067], // 初始化地图中心点
      mapStyle: 'amap://styles/grey'
    });
  }

  pointsToMarkers(points) {
    const markers = [];
    points.forEach(item => {
      const marker = new AMap.Marker({
        position: new AMap.LngLat(item.lng, item.lat),
        icon: 'https://static.justdodo.cn/xiaohan/38c2b6dda19064af5c7806fbf266fafd2d5dd73a.svg',
        offset: new AMap.Pixel(-13, -30),
        extData: {id: item._id}
      });
      marker.setLabel({
        offset: new AMap.Pixel(40, 20),
        content: `<div class='info'>${item.title}</div>`
      });
      markers.push(marker);
    });
    return markers;
  }

  addPoint(points) {
    const markers = this.pointsToMarkers(points);
    if (this.overlayGroup) {
      this.map.remove(this.overlayGroup);
    }
    this.overlayGroup = new AMap.OverlayGroup(markers);
    this.map.add(this.overlayGroup);
  }

  addCluster(points) {
    if (this.cluster) {
      this.cluster.setMap(null);
    }
    const markers = this.pointsToMarkers(points);
    this.cluster = new AMap.MarkerClusterer(this.map, markers, {gridSize: 50});
  }

  ngOnChanges(changes: SimpleChanges) {
    const firstChange = changes.points.firstChange;
    if (firstChange) {
      this.initMap();
    }
    const points = changes.points.currentValue;
    // this.addPoint(points);
    this.addCluster(points);
  }

}
